package com.heima.es.utils;

import com.alibaba.fastjson.JSON;
import com.heima.es.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class EsUtils {


    public static void main(String[] args) throws IOException {

        RestHighLevelClient client= new RestHighLevelClient(
                RestClient.builder(new HttpHost("192.168.200.150", 9200, "http"))
        );

        BulkRequest request=new BulkRequest("user");
        //1. 从数据库查询文档数据
        List<User> users = Arrays.asList(
                new User(41L, "Rose", 118, "1", "Rose同学在传智播客学表演"),
                new User(42L, "Jack", 138, "1", "Jack同学在黑马学JavaEE"),
                new User(43L, "小红", 213, "0", "小红同学在传智播客学唱歌"),
                new User(44L, "小明", 210, "1", "小明同学在黑马学JavaSE"),
                new User(45L, "达摩", 313, "1", "达摩和尚在达摩院学唱歌"),
                new User(46L, "鲁班", 214, "1", "鲁班同学走在乡间小路上"),
                new User(47L, "孙尚香", 126, "0", "孙尚香同学想带阿斗回东吴"),
                new User(48L, "李白", 217, "1", "李白同学在山顶喝着酒唱着歌"),
                new User(49L, "甄姬", 218, "0", "甄姬同学弹奏一曲东风破"),
                new User(40L, "虞姬", 217, "0", "虞姬同学在和项羽谈情说爱")
        );

        for (User user : users) {
            IndexRequest indexRequest = new IndexRequest();
            String jsonString = JSON.toJSONString(user);
            indexRequest.source(jsonString, XContentType.JSON);

            request.add(indexRequest);
        }

        BulkResponse response=client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response+"=========================");

        client.close();
    }
}
